package com.jht.bletool2java.activity.homepage.fragment.bledevice.adapter;


import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.xtoast.OnClickListener;
import com.hjq.xtoast.XToast;
import com.jht.bletool2java.R;
import com.jht.bletool2java.activity.blepage.BleDataActivity;
import com.jht.bletool2java.activity.homepage.fragment.bledevice.bean.BLEDevice;
import com.jht.bletool2java.util.ByteUtil;
import com.jht.bletool2java.widget.ChangeColorTextView;

import java.util.ArrayList;
import java.util.List;

public class BleDeviceAdapter extends RecyclerView.Adapter<BleDeviceAdapter.BleDeviceViewHolder> {
    //payloads flag
    public static final String payload_dBm = "mTvBleDbm";
    public static final String BLE_DEVICE = "BLE_DEVICE";
    private static final String TAG = "BleDeviceAdapter";
    public int count = 1;
    private Activity mContext;
    private List<BLEDevice> ble_data = new ArrayList<>();

    private XToast showBleBroadcastData;
    private ScanCallback scanCallback;

    public BleDeviceAdapter(Activity mContext) {
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public BleDeviceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.i(TAG, "onCreateViewHolder: ");
        View inflate = LayoutInflater.from(mContext).inflate(viewType, parent, false);
        return new BleDeviceViewHolder(inflate, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull BleDeviceViewHolder viewHolder, final int position) {
        int itemViewType = getItemViewType(position);
        if (itemViewType == R.layout.layout_no_data) {
            return;
        }
        if (itemViewType == R.layout.item_ble_device) {
            BLEDevice bleDevice = ble_data.get(position);
            viewHolder.mBtnDeviceName.setText(bleDevice.getDevice().getName());
            viewHolder.mBtnDeviceMac.setText(bleDevice.getDevice().getAddress());
            String currentDBM = "" + bleDevice.getRssi() + " dBm";
            viewHolder.mTvBleDbm.setText(currentDBM);
            viewHolder.mBtnConnectBle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startBleDataActivity(bleDevice);
                    //停止扫描
                    if (scanCallback!=null){
                        scanCallback.stopBtScan();
                    }
                }
            });

            viewHolder.mLlBleLayoutParent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //显示BLE广播数据
                    showBleBroadcastDataRecord(position);
                }
            });
        }
    }

    private void startBleDataActivity(BLEDevice bleDevice) {
        Intent intent = new Intent(mContext, BleDataActivity.class);
        intent.putExtra(BleDeviceAdapter.BLE_DEVICE, bleDevice);
        mContext.startActivity(intent);
    }

    private void showBleBroadcastDataRecord(int position) {
        Log.d(TAG, "showBleBroadcastDataRecord: ");
        initDialog();
        String broadcastData = mContext.getResources().getString(R.string.broadcast_data) + ByteUtil.getHexStringNoSplit(ble_data.get(position).getScanRecord());
        showBleBroadcastData.setText(R.id.tv_ble_broadcast_data, broadcastData);
        showBleBroadcastData.show();
    }

    private void initDialog() {
        showBleBroadcastData = new XToast(mContext)
                .setWindowFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                .setDuration(0)
                .setView(R.layout.dialog_show_ble_broadcast_data)
                .setAnimStyle(android.R.style.Animation_Dialog)
                .setOnClickListener(R.id.btn_close_ble_broadcast_dialog, new OnClickListener() {
                    @Override
                    public void onClick(XToast toast, View view) {
                        toast.cancel();
                    }
                }).setOnClickListener(R.id.ll_setting_parent_new, new OnClickListener() {
                    @Override
                    public void onClick(XToast toast, View view) {
                        toast.cancel();
                    }
                });

    }

    @Override
    public void onBindViewHolder(@NonNull BleDeviceViewHolder holder, int position, @NonNull List<Object> payloads) {
        if (payloads.size() == 0) {
            super.onBindViewHolder(holder, position, payloads);
        } else {
            BLEDevice bleDevice = ble_data.get(position);
            for (Object payload : payloads) {
                switch (String.valueOf(payload)) {
                    case BleDeviceAdapter.payload_dBm:
                        String text = bleDevice.getRssi() + mContext.getString(R.string.ble_params);
                        holder.mTvBleDbm.setText(text);
                        holder.mTvBleDbm.setTextColorIn2S();
                        break;
                    default:
                        break;
                }
            }
        }


    }

    @Override
    public int getItemCount() {
        return ble_data.size() == 0 ? 1 : ble_data.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (ble_data.size() == 0) {
            return R.layout.layout_no_data;
        }
        return R.layout.item_ble_device;
    }

    public void addDevice(BLEDevice device) {
        updateDeviceData(device);
    }

    public void updateDeviceData(BLEDevice device) {
        //首先检测是否存在次device
        for (int i = 0; i < ble_data.size(); i++) {
            BLEDevice bleDevice = ble_data.get(i);
            if (bleDevice.getDevice().getAddress().equals(device.getDevice().getAddress())) {
                if (bleDevice.getRssi() != device.getRssi()) {
                    bleDevice.setRssi(device.getRssi());
                    notifyItemChanged(i, BleDeviceAdapter.payload_dBm);
                }
                bleDevice.setScanRecord(device.getScanRecord());
                return;
            }
        }
        ble_data.add(device);
        notifyItemInserted(ble_data.size() + 1);
    }

    public void clear() {
        ble_data.clear();
        count = 1;
        notifyDataSetChanged();
    }

    public void setScanCallback(ScanCallback scanCallback) {
        this.scanCallback = scanCallback;
    }

    public interface ScanCallback {
        void stopBtScan();
    }

    public static class BleDeviceViewHolder extends RecyclerView.ViewHolder {

        TextView mBtnDeviceName;
        TextView mBtnDeviceMac;
        ChangeColorTextView mTvBleDbm;
        Button mBtnConnectBle;
        LinearLayout mLlBleLayoutParent;

        public BleDeviceViewHolder(@NonNull View itemView, int viewType) {
            super(itemView);
            if (viewType == R.layout.item_ble_device) {
                mBtnDeviceName = itemView.findViewById(R.id.btn_device_name);
                mBtnDeviceMac = itemView.findViewById(R.id.btn_device_mac);
                mTvBleDbm = itemView.findViewById(R.id.tv_ble_dbm);
                mBtnConnectBle = itemView.findViewById(R.id.btn_connect_ble);
                mLlBleLayoutParent = itemView.findViewById(R.id.ll_ble_layout_parent);
            }

        }
    }
}
